 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=207 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:36 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Compare and sort Strings
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='comparable,Comparator,TreeMap,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Compare and sort Strings</div>

<div class='main-body'>
 <br>

Comparing and sorting Strings is a bit tricky, and should be done with some care. 
This is particularly true when the text is displayed to the end user, or when working with localized text.

<P><span class='highlight'>There are <em>two</em> fundamentally different ways of comparing strings</span> :
<ul>
<li>simple <em>Unicode</em> ordering - used by <tt><a href='http://java.sun.com/javase/6/docs/api/java/lang/String.html'>String</a></tt>
<li><em>localized</em> ordering (the kind expected by an end user) - used by <tt><a href='http://java.sun.com/javase/6/docs/api/java/text/Collator.html'>Collator</a></tt>
</ul>

This causes problems, because :
<ul>
<li>there are only occasional mismatches between the two styles
<li>it's easy to forget to apply the distinction, when needed
</ul>

Commonly used <tt>String</tt> methods such as <tt>String.<a href='http://java.sun.com/javase/6/docs/api/java/lang/String.html#equalsIgnoreCase(java.lang.String)'>equalsIgnoreCase</a>(String)</tt> and <tt>String.<a href='http://java.sun.com/javase/6/docs/api/java/lang/String.html#compareTo(java.lang.String)'>compareTo</a>(String)</tt> can be dangerous to use, depending on the context.
The reason is that programmers tend to apply them to tasks they really aren't meant for, simply out of habit.

<P><span class='highlight'>The fundamental difference is that <em>localized</em> comparison depends on <tt>Locale</tt>, while <tt>String</tt> is largely <em>ignorant</em> of <tt>Locale</tt>.</span> 
Here is a quote from <em>The Java Programming Language</em> by Arnold, Gosling, and Holmes :

<P><em>"You should be aware that internationalization and localization issues of full Unicode strings are not addressed
with [String] methods. For example, when you're comparing two strings to determine which is 'greater', characters 
in strings are compared numerically by their Unicode values, not by their localized notion of order."</em>

<P>The only robust way of doing <em>localized</em> comparison or sorting of <tt>String</tt>s, in the manner expected by an end user, is to use a <tt><a href='http://java.sun.com/javase/6/docs/api/java/text/Collator.html'>Collator</a></tt>, not the methods of the <tt>String</tt> class.

<P><b>Example 1 - Unicode Ordering</b>
<P>Here is an example of simple Unicode ordering of Strings.
Note the use of <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html#CASE_INSENSITIVE_ORDER">String.CASE_INSENSITIVE_ORDER</a>, 
an implementation of <a href="http://java.sun.com/javase/6/docs/api/java/util/Comparator.html">Comparator</a>.

<P>Reminder - the following items are important with <em>any</em> form of comparison or sorting :
<ul>
<li>the 
<a href="http://java.sun.com/javase/6/docs/api/java/util/Comparator.html">Comparator</a> and 
<a href="http://java.sun.com/javase/6/docs/api/java/lang/Comparable.html">Comparable</a> interfaces
<li>the various <tt>sort</tt> methods of 
<a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html">Collections</a> and 
<a href="http://java.sun.com/javase/6/docs/api/java/util/Arrays.html">Arrays</a>
</ul>
<br>
<PRE>

<span class='keyword'>import</span> java.util.*;

<span class='comment'>/** Sorting Strings in Unicode order. */</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> SortStringsNoLocale {

  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main(String... aArgs){
    List&lt;String&gt; insects = Arrays.asList(<span class='literal'>"Wasp"</span>, <span class='literal'>"ant"</span>, <span class='literal'>""</span>, <span class='literal'>"Bee"</span>);
    log(insects + <span class='literal'>" - Original Data"</span>);
    sortList(insects);
    log(insects + <span class='literal'>" - Sorted Data"</span>);

    Map&lt;String,String&gt; capitals = <span class='keyword'>new</span> LinkedHashMap&lt;String, String&gt;();
    capitals.put(<span class='literal'>"finland"</span>, <span class='literal'>"Helsinki"</span>);
    capitals.put(<span class='literal'>"United States"</span>, <span class='literal'>"Washington"</span>);
    capitals.put(<span class='literal'>"Mongolia"</span>, <span class='literal'>"Ulan Bator"</span>);
    capitals.put(<span class='literal'>"Canada"</span>, <span class='literal'>"Ottawa"</span>);
    log(capitals + <span class='literal'>" - Original Data"</span>);
    log(sortMapByKey(capitals) + <span class='literal'>" - Sorted Data"</span>);
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> sortList(List&lt;String&gt; aItems){
    Collections.sort(aItems, String.CASE_INSENSITIVE_ORDER);
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> log(Object aObject){
    System.out.println(String.valueOf(aObject)); 
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> Map&lt;String, String&gt; sortMapByKey(Map&lt;String, String&gt; aItems){
    TreeMap&lt;String, String&gt; result = 
      <span class='keyword'>new</span> TreeMap&lt;String, String&gt;(String.CASE_INSENSITIVE_ORDER)
    ;
    result.putAll(aItems);
    <span class='keyword'>return</span> result;
  }
} 
</PRE>
<br>
The class outputs the following :
<PRE>
[Wasp, ant, , Bee] - Original Data
[, ant, Bee, Wasp] - Sorted Data
{finland=Helsinki, United States=Washington, Mongolia=Ulan Bator, Canada=Ottawa} - Original Data
{Canada=Ottawa, finland=Helsinki, Mongolia=Ulan Bator, United States=Washington} - Sorted Data
</PRE>


<P><b>Example 2 - Localized Ordering</b>
<P>Here's an example of using a <tt><a href='http://java.sun.com/javase/6/docs/api/java/text/Collator.html'>Collator</a></tt> to perform <em>localized</em> sorting and comparison of Strings.
Note the importance of <tt>Collator</tt> 'strength' for fine-tuning the comparison. 
To ignore case, for example, either <tt>PRIMARY</tt> or <tt>SECONDARY</tt> strength can be used.
<br>
<PRE>

<span class='keyword'>import</span> java.text.Collator;
<span class='keyword'>import</span> java.util.*;

<span class='comment'>/** Use Collator to sort and compare text.*/</span>
<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> SimpleCollator {

  <span class='comment'>/** Simple harness to exercise the code.  */</span>
  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String... aArguments) {
    <span class='comment'>//This data is based on an example in Java Class Libraries, 
</span>    <span class='comment'>//by Chan, Lee, and Kramer
</span>    List&lt;String&gt; words = Arrays.asList(<span class='literal'>"Äbc"</span>, <span class='literal'>"äbc"</span>, <span class='literal'>"Àbc"</span>, <span class='literal'>"àbc"</span>, <span class='literal'>"Abc"</span>, <span class='literal'>"abc"</span>, <span class='literal'>"ABC"</span>);
    
    log(<span class='literal'>"Different 'Collation Strength' values give different sort results: "</span>);
    log(words + <span class='literal'>" - Original Data"</span>);
    sort(words, Strength.Primary);
    sort(words, Strength.Secondary);
    sort(words, Strength.Tertiary);
    
    log(EMPTY_LINE);
    log(<span class='literal'>"Case kicks in only with Tertiary Collation Strength  : "</span>);
    List&lt;String&gt; wordsForCase = Arrays.asList(<span class='literal'>"cache"</span>, <span class='literal'>"CACHE"</span>, <span class='literal'>"Cache"</span>);
    log(wordsForCase + <span class='literal'>" - Original Data"</span>);
    sort(wordsForCase, Strength.Primary);
    sort(wordsForCase, Strength.Secondary);
    sort(wordsForCase, Strength.Tertiary);
    
    log(EMPTY_LINE);
    log(<span class='literal'>"Accents kick in with Secondary Collation Strength."</span>);
    log(<span class='literal'>"Compare with no accents present: "</span>);
    compare(<span class='literal'>"abc"</span>, <span class='literal'>"ABC"</span>, Strength.Primary);
    compare(<span class='literal'>"abc"</span>, <span class='literal'>"ABC"</span>, Strength.Secondary);
    compare(<span class='literal'>"abc"</span>, <span class='literal'>"ABC"</span>, Strength.Tertiary);
    
    log(EMPTY_LINE);
    log(<span class='literal'>"Compare with accents present: "</span>);
    compare(<span class='literal'>"abc"</span>, <span class='literal'>"ÀBC"</span>, Strength.Primary);
    compare(<span class='literal'>"abc"</span>, <span class='literal'>"ÀBC"</span>, Strength.Secondary);
    compare(<span class='literal'>"abc"</span>, <span class='literal'>"ÀBC"</span>, Strength.Tertiary);
  }

  <span class='comment'>// PRIVATE //
</span>  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> String EMPTY_LINE = <span class='literal'>""</span>;
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>final</span> Locale TEST_LOCALE = Locale.FRANCE;
  
  <span class='comment'>/** Transform some Collator 'int' consts into an equivalent enum. */</span>
  <span class='keyword'>private</span> <span class='keyword'>enum</span> Strength {
    Primary(Collator.PRIMARY), <span class='comment'>//base char
</span>    Secondary(Collator.SECONDARY), <span class='comment'>//base char + accent
</span>    Tertiary(Collator.TERTIARY), <span class='comment'>// base char + accent + case
</span>    Identical(Collator.IDENTICAL); <span class='comment'>//base char + accent + case + bits
</span>    
    <span class='keyword'>int</span> getStrength() { <span class='keyword'>return</span> fStrength; }
    
    <span class='keyword'>private</span> <span class='keyword'>int</span> fStrength;
    <span class='keyword'>private</span> Strength(<span class='keyword'>int</span> aStrength){
      fStrength = aStrength;
    }
  }
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> sort(List&lt;String&gt; aWords, Strength aStrength){
    Collator collator = Collator.getInstance(TEST_LOCALE);
    collator.setStrength(aStrength.getStrength());
    Collections.sort(aWords, collator);
    log(aWords.toString() + <span class='literal'>" "</span> + aStrength);
  }
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> compare(String aThis, String aThat, Strength aStrength){
    Collator collator = Collator.getInstance(TEST_LOCALE);
    collator.setStrength(aStrength.getStrength());
    <span class='keyword'>int</span> comparison = collator.compare(aThis, aThat);
    <span class='keyword'>if</span> ( comparison == <span class='literal'>0</span> ) {
      log(<span class='literal'>"Collator sees them as the same : "</span> + aThis + <span class='literal'>", "</span> + aThat + <span class='literal'>" - "</span> + aStrength);
    }
    <span class='keyword'>else</span> {
      log(<span class='literal'>"Collator sees them as DIFFERENT  : "</span> + aThis + <span class='literal'>", "</span> + aThat + <span class='literal'>" - "</span> + aStrength);
    }
  }
  
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> log(String aMessage){
    System.out.println(aMessage);
  }
}  
</PRE>
<br>
This class outputs the following :
<PRE>
Different 'Collation Strength' values give different sort results: 
[Äbc, äbc, Àbc, àbc, Abc, abc, ABC] - Original Data
[Äbc, äbc, Àbc, àbc, Abc, abc, ABC] Primary
[Abc, abc, ABC, Àbc, àbc, Äbc, äbc] Secondary
[abc, Abc, ABC, àbc, Àbc, äbc, Äbc] Tertiary

Case kicks in only with Tertiary Collation Strength  : 
[cache, CACHE, Cache] - Original Data
[cache, CACHE, Cache] Primary
[cache, CACHE, Cache] Secondary
[cache, Cache, CACHE] Tertiary

Accents kick in with Secondary Collation Strength.
Compare with no accents present: 
Collator sees them as the same : abc, ABC - Primary
Collator sees them as the same : abc, ABC - Secondary
Collator sees them as DIFFERENT: abc, ABC - Tertiary

Compare with accents present: 
Collator sees them as the same : abc, ÀBC - Primary
Collator sees them as DIFFERENT: abc, ÀBC - Secondary
Collator sees them as DIFFERENT: abc, ÀBC - Tertiary
</PRE>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicAction3eed-2.html?Id=10'>Implementing compareTo</a> <br>
 
  
  <a href='TopicAction95c3-2.html?Id=18'>Determine if Strings are equal</a> <br>
 
  
  <a href='TopicActionc6f5-2.html?Id=65'>Choosing the right Collection</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='207'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=207 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:36 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
